package com.heima.xxljob.job;

import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @author jack
 * @data 2024 10:27
 */
@Component
@Slf4j
public class JobDemo1 {

    @Value("${xxl.job.executor.port}")
    private String port;

    //给10个用户发优惠券
    @XxlJob("quickstartHandler")
    public void method1() {
        //0. 获取分片广播计算参数
        int index = XxlJobHelper.getShardIndex();       //获取当前注册节点索引  9998 --> 0   9999 --> 1
        int total = XxlJobHelper.getShardTotal();       //注册节点总数

        //1. 获取系统用户
        List<Integer> users = getUsers();

        //2. 遍历用户，给每个用户发放优惠券
        for (int i = 0; i < users.size(); i++) {
            //3. 拿到当前用户信息
            Integer user = users.get(i);

            //4. 进行分片计算，确定当前操作节点
            if (i % total == index){
                log.info(port + "给"+user+"号用户发优惠券");
            }
        }
    }

    //获取用户信息
    public List<Integer> getUsers() {
        List<Integer> users = new ArrayList<>();
        for (int i = 1; i <= 10; i++) {
            users.add(i);
        }
        return users;
    }

}
